<template>
  <div style="margin-top: 20px;">
    <h3>柱状图</h3>
    <BasicForm @register="register" @submit="handleSubmit" />
    <div ref="chartRef" :style="{ height, width }"></div>
  </div>
</template>

<script lang="ts" setup>
  import { PropType, ref, Ref } from 'vue';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { useECharts } from '@/hooks/web/useECharts';

  const props = defineProps({
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: 'calc(100vh - 78px)',
    },
    queryResult: [],
    keyOptions: [],
  });

  const formSchema: FormSchema[] = [
    {
      field: 'x',
      label: 'X轴',
      component: 'Select',
      required: true,
      componentProps: {
        options: props.keyOptions,
      },
    },
    {
      field: 'y',
      label: 'Y轴',
      component: 'Select',
      required: true,
      componentProps: {
        options: props.keyOptions,
      },
    },
  ];

  const [register] = useForm({
    baseColProps: { span: 10 },
    labelWidth: 80,
    showActionButtonGroup: true,
    schemas: formSchema,
  });

  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
  
  function handleSubmit(values) {
    let xData = [];
    let yData = [];
    let dataMap = new Map();
    for (const item of props.queryResult) {
      const x = item[values.x];
      const y = item[values.y];
      if (dataMap.has(x)) {
        dataMap.set(x, dataMap.get(x) + y);
      } else {
        dataMap.set(x, y);
      }
    }
    dataMap.forEach((value, key) => {
      xData.push(key);
      yData.push(value);
    });
    setOptions({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
      xAxis: [
        {
          type: 'category',
          data: xData,
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: 'Direct',
          type: 'bar',
          barWidth: '60%',
          data: yData
        }
      ]
    });
  };
</script>